import os
from dotenv import load_dotenv, find_dotenv
import pymysql
import logging

logging.basicConfig(level=logging.INFO,
                    format='%(asctime)s - %(levelname)s: %(message)s')

# 加载 .env 文件中定义的环境变量
_ = load_dotenv(find_dotenv())

class MysqlClient:
    def __init__(self):
        host = os.getenv('MYSQL_HOST')
        user = os.getenv('MYSQL_USER')
        password = os.getenv('MYSQL_PASSWORD')
        port = int(os.getenv('MYSQL_PORT'))
        db = os.getenv('MYSQL_DB')
        self.db_connection = pymysql.connect(host=host, user=user, password=password, port=port, db=db)
        self.cursor = self.db_connection.cursor()
        self.db_connection.autocommit(False)
        
    def insert_one(self, table, data):
        keys = ','.join(data.keys())
        values = ','.join(['%s'] * len(data))
        sql = f'INSERT INTO {table}({keys}) VALUES({values})'
        self.insert_core(sql, tuple(data.values()))

    def insert_core(self, sql, params=None):
        try:
            self.cursor.execute(sql, params)
            self.db_connection.commit()
        except pymysql.Error as e:
            self.db_connection.rollback()
            logging.error(f"MySQL 错误: {e}")

    def __enter__(self):
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        self.cursor.close()
        self.db_connection.close()

    def __del__(self):
        try:
            if hasattr(self, 'cursor') and self.cursor:
                self.cursor.close()
            if hasattr(self, 'db_connection') and self.db_connection:
                self.db_connection.close()
        except:
            pass
